package com.wesley.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.UUID;

/**
 * @author:wesley
 */
public class RedisDistributeLock {

    private JedisPool jedisPool;

    public RedisDistributeLock(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }


    /**
     *
     * 获取锁并且锁住
     *
     * @param lockName 锁key
     * @param acquireTime 获取连接超时的时间
     * @param outTime 锁的超时时间
     * @return 锁标识
     */
    public String lockWithTimeout(String lockName, long acquireTime, long outTime){

        String redId = null;
        Jedis conn = null;
        try {
            conn =  jedisPool.getResource();
            String id = UUID.randomUUID().toString();
            String lockkey = "lock"+lockName;
            int expireTime = (int) (outTime/1000);
            //访问结束时间
            long end = System.currentTimeMillis() + acquireTime;

            //没有超时
            while (System.currentTimeMillis() < end) {

                if (conn.setnx(lockkey, id) == 1){
                    conn.expire(lockkey, expireTime);
                    redId = id;
                    return redId;
                }

                if (conn.ttl(lockkey) == -1){
                    conn.expire(lockkey, expireTime);
                }

                Thread.sleep(10);
            }
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            if (conn != null) {
                conn.close();
            }
        }
        return redId;
    }


    /**
     * 释放锁
     *
     * @param lockName
     * @param id
     * @return
     */
    public boolean releaseLock(String lockName,String id){
        Jedis conn = null;
        String key = "lock"+lockName;
        boolean retFlag= false;

        try {
            conn = jedisPool.getResource();
            while (true) {
                conn.watch(key);
                String val = conn.get(key);

                if (val != null && id.equals(val)){
                    Transaction transaction = conn.multi();
                    transaction.del(key);

                    List<Object> list = transaction.exec();
                    if (list == null) {
                        continue;
                    }

                    retFlag = true;
                }
                conn.unwatch();
                break;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        } finally {
            if (conn!=null){
                conn.close();
            }
        }
        return retFlag;
    }

}
